package com.module.demo.service.impl;

import com.module.demo.service.ProductService;
import com.module.demo.dal.model.FruitDO;
import com.module.demo.service.model.bo.OrderItemBO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: ProductServiceImpl
 * @description: ProductServiceImpl 描述
 * @author: kangzeng.ckz
 * @date: 2022/10/12
 **/
@Service
public class ProductServiceImpl implements ProductService {

    private Map<String, FruitDO> fruitBOMap = new HashMap<>();

    @PostConstruct
    void init() {
        // 数据模拟，真实情况不需要这个map
        FruitDO apple = new FruitDO();
        apple.setName("apple");
        apple.setPrice(8.0);
        fruitBOMap.put("apple", apple);
        FruitDO strawberry = new FruitDO();
        strawberry.setName("strawberry");
        strawberry.setPrice(13.0);
        fruitBOMap.put("strawberry", strawberry);
    }

    @Override
    public Double getOrderPrice(List<OrderItemBO> itemList) throws Exception {

        // 1. 参数检查
        if (CollectionUtils.isEmpty(itemList)) {
            throw new Exception("Order is empty!");
        }

        // 2.计算所有水果订单价格
        Iterator<OrderItemBO> it = itemList.iterator();
        Double total = 0.0;
        while (it.hasNext()) {
            OrderItemBO item = it.next();
            total += getItemPrice(item);
        }
        return total;
    }

    @Override
    public Boolean addFruit(FruitDO fruit) {
        List<String> dataList = fruitBOMap.keySet().stream().collect(Collectors.toList());
        if (dataList.contains(fruit.getName())) {
            System.out.println("fruit "+fruit.getName()+" already exist.");
            return false;
        }
        fruitBOMap.put(fruit.getName(), fruit);
        return true;
    }

    @Override
    public Double getOrder100DiscountPrice(Double price) {
        double off = Math.floor(price / 100) * 10;
        price -= off;
        return price;
    }

    private Double getItemPrice(OrderItemBO item) throws Exception {
        List<String> dataList = fruitBOMap.keySet().stream().collect(Collectors.toList());
        if (!dataList.contains(item.getFruitName())) {
            throw new Exception("invalid fruit name:" + item.getFruitName());
        }
        FruitDO fruitBO = fruitBOMap.get(item.getFruitName());
        Double price = fruitBO.getPrice();
        Double discount = item.getDiscount();
        if (discount != null && discount != 0 && discount <= 1) {
            price *= discount;
        }
        price *= item.getCount();
        return price;
    }

}
